﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System.Data.Repository;
using System.Linq;

namespace nMongo
{
    /// <summary>
    /// Represents a repository class for an entity.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public partial class MongoRepository<T> : IRepository<T>
        where T : class
    {
        #region Protected Fields
        protected MongoCollection<T> _collection;
        #endregion

        #region Constructors (2 overloads)
        /// <param name="mongoUri">The URI that locates the MongoDB database.</param>
        /// <param name="databaseName">The database name.</param>
        public MongoRepository(string mongoUri, string databaseName) 
            : this(new MongoEngine(mongoUri, databaseName))
        { }

        /// <param name="connection">A MongoEngine connection with database settings.</param>
        public MongoRepository(MongoEngine connection)
        {
            this.Connection = connection;
            _collection = Connection.GetCollection<T>();
        }
        #endregion

        #region Properties
        public MongoCollection<T> OriginalCollection
        {
            get
            {
                if (_collection == null)
                    _collection = Connection.GetCollection<T>();
                return _collection;
            }
        }

        public MongoCollection<T> MortalCollection
        {
            get
            {
                if (_collection == null)
                    _collection = Connection.GetMortalCollection<T>();
                return _collection;
            }
        }

        /// <summary>
        /// Current connection of the repository.
        /// </summary>
        public MongoEngine Connection { get; set; }

        /// <summary>
        /// IQueryable for the current collection.
        /// </summary>
        public IQueryable<T> CollectionQuery
        {
            get { return OriginalCollection.AsQueryable(); }
        }
        #endregion
    }
}
